/* -*- C++ -*- */

//=============================================================================
/*
* @author Feloweria <380374483@qq.com>
* Copyright (C) Feloweria
*
* $ID 2014-05-14 11:25:19 AM
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
* @version 1.0
*/
//=============================================================================


#include "Network/SocketManager.h"
#include "Network/SocketThread.h"
#include "Network/Socket.h"

#ifdef __LINUX__
	#include <sys/epoll.h>
#endif

FELOWRIA_BEGIN

SocketManager* SocketManager::instance = NULL;

SocketManager::SocketManager()
{
#ifdef __WINDOWS__
	WSAData wsaData;
	if (WSAStartup(MAKEWORD(2, 2), &wsaData))
		LOG_ERROR("SocketManager::SocketManager WSAStartup Fail");
#endif
}

SocketManager::~SocketManager()
{
	delete [] thread_list;
}

SocketManager* SocketManager::Instance()
{
	if(instance)
		return instance;

	return instance = new SocketManager;
}

SocketThread* SocketManager::GetFreeThread()
{
	for(SocketThread *thread = thread_list,*thread_end = thread_list + thread_size;thread < thread_end;++thread)
	{
		if(!thread->IsFull())
			return thread;
	}

	LOG_TRACE(" SocketManager::GetFreeThread socket is full");
	return NULL;
}

bool SocketManager::SpawnSocketThread(int32 size)
{
	if(size <= 0)
		return false;

	thread_list = new SocketThread[size];

	for(int32 i = 0;i < size;++i)
		thread_list[i].ExcuteTask();
	
	thread_size = size;
	return true;
}

FELOWRIA_END
